<?php
/**
 * KA套餐管理控制器
 */
namespace Beerus\Modules\DesignerAdv\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DesignerCompetition2021\audit\DcAuditFirstResult;
use Doraemon\model\KaManage\KaDesignerPerch;
use Doraemon\model\KaManage\KaResourceCombo;
use Doraemon\model\KaManage\KaResourceDetail;
use Doraemon\model\Member;
use Doraemon\model\DesignerCompetition2021\audit\admin\DcAuditFirstWorkAdmin;
use Doraemon\tools\ParamsCheck;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;

class KaDesignerController extends Controller {

    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content) {
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $total = KaDesignerPerch::getTotalPerchDesignerCnt();
        $list = KaDesignerPerch::getTotalPerchDesignerList($page, $pageSize);
        foreach ($list as &$item) {
            $item['nick'] = Member::getNickByUid($item['uid']);
        }
        unset($item);
        $gridModel = new pGridDataModel($list, $total['cnt'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(4, function ($filter) {
                        $filter->equal('combo_type', '套餐类型')->placeholder('请输入套餐类型');
                    });
                    $filter->column(4, function ($filter) {
                        $filter->equal('combo_name', '套餐名称')->placeholder('请输入套餐名称');
                    });
                    $filter->expand();
                });

                $grid->column('uid', '设计师UID');
                $grid->column('nick', '设计师昵称')->display(function() {
                    return "<a href='/admin/DesignerAdv/designer'>".$this->nick."</a>";
                });
                $grid->column('add_time', '首次占位时间');
                $grid->disableActions();
            }
        );
        return $content
            ->header('KA广告套餐列表')
            ->row($gridList);
    }

    public function edit(Request $request, Content $content, $id = 0) {
        $data = KaResourceCombo::get('*', ['id' => $id]);
        if ($data) {
            $data['combo_setting'] = json_decode($data['combo_setting'], true);
        }
        $form = new Form($data);
        if (!empty($id)) {
            $form->text('id', '套餐ID')->readOnly();
            $form->text('combo_type', '套餐类型')->readOnly();
        } else {
            $form->text('combo_type', '套餐类型')->required();
        }
        $form->text('combo_name', '套餐名称')->required();
        $form->table('combo_setting', '套餐天数设置', function ($table) {
            $table->select('resource_type', '资源位类型')
                ->options(KaResourceCombo::RESOURCE_DETAIL_TITLE)
                ->load('resource_detail_id', '/admin/DesignerAdv/combo/resourceDetail')
                ->required();
            $table->select('resource_detail_id', '资源位对应位置')
                ->options($this->getAllResourceDetailList())
                ->required();
            $table->text('combo_day', '可投放天数');
        });
        $form->confirm('确定提交吗？');
        $form->action('/admin/DesignerAdv/combo/save');

        $header = '信息修改';
        $tab = new Tab();
        $tab->add($header, $form->render());
        return $content->header($header)
            ->breadcrumb(
                ['text' => 'KA广告套餐列表'],
                ['text' => '编辑套餐信息'],
            )->row($tab);
    }

    public function resourceDetailList(Request $request) {
        $resourceType = $request->input('q', 1);
        $data = $this->getAllResourceDetailList($resourceType);
        $format = array_map(function ($k, $v) {
            return [
                'id'   => $k,
                'text' => $v,
            ];
        }, array_keys($data), $data);
        return response()->json($format);
    }

    public function getAllResourceDetailList($resourceType = 0) {
        $condition = [];
        if ($resourceType) {
            $condition['type'] = $resourceType;
        }
        $resourceDetails = KaResourceDetail::select('*', $condition);
        $data = [];
        foreach ($resourceDetails as $item) {
            switch ($item['type']) {
                case 4:
                    $item['name'] = 'APP-开屏';
                    break;
                case 5:
                    $item['name'] = '第三条';
                    break;
                case 6:
                    $item['name'] = '第二条';
                    break;
                case 7:
                    $item['name'] = '微博-好好住';
                    break;
                case 8:
                    $item['name'] = '微博-营造家';
                    break;
            }
            $data[$item['id']] = $item['name'];
        }
        return $data;
    }

    public function save(Request $request) {
        $id = $request->input('id');
        $comboName = $request->input('combo_name');
        $comboType = $request->input('combo_type');
        $comboSetting = $request->input('combo_setting');
        $comboSetting = array_values($comboSetting);
        foreach ($comboSetting as $combo) {
            if (!ParamsCheck::isPositiveNumber($combo['combo_day'])) {
                $error = new MessageBag(['title' => '套餐天数请输入正数']);
                return back()->with(compact('error'));
            }
        }
        $data = [
            'combo_name' => $comboName,
            'combo_setting' => json_encode($comboSetting),
            'admin_uid' => Admin::user()->id
        ];
        if (empty($id)) { // 新增
            $data['combo_type'] = $comboType;
            if (KaResourceCombo::get('*', ['combo_type' => $comboType, 'data_status' => KaResourceCombo::STATUS_NORMAL])) {
                $error = new MessageBag(['title' => '该套餐类型已存在']);
                return back()->with(compact('error'));
            }
            if (!KaResourceCombo::addInfo($data)) {
                $error = new MessageBag(['title' => '新增套餐失败']);
                return back()->with(compact('error'));
            }
        } else {
            if (!KaResourceCombo::updateInfo($data, ['id' => $id])) {
                $error = new MessageBag(['title' => '修改套餐信息失败']);
                return back()->with(compact('error'));
            }
        }

        $success = new MessageBag(['title' => '操作成功']);
        return redirect('/admin/DesignerAdv/combo')->with(compact('success'));
    }

    public function del($id) {
        $data = KaResourceCombo::get('*', ['id' => $id]);
        if ($data) {
            if (!KaResourceCombo::updateInfo(['data_status' => KaResourceCombo::STATUS_DELETE], ['id' => $id])) {
                return response()->json([
                    'status' => false,
                    'message' => "删除失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "该套餐不存在",
            ]);
        }
    }
}
